//
//  ShoppingViewController.swift
//  许鲜
//
//  Created by hbl on 16/4/22.
//  Copyright © 2016年 hbl. All rights reserved.
//

import UIKit

class ShoppingViewController: UIViewController {
    var total:UILabel?
    lazy var mainTableView:UITableView = {
        let mainTableView = UITableView()
        mainTableView.frame = CGRectMake(0, 0, mainW, mainH)
        mainTableView.registerNib(UINib.init(nibName: "ShoppingTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        mainTableView.separatorStyle = UITableViewCellSeparatorStyle.None
        mainTableView.delegate = self
        mainTableView.dataSource = self
        mainTableView.rowHeight = 100
        mainTableView.contentInset = UIEdgeInsetsMake(25, 0, 109, 0)
        mainTableView.scrollIndicatorInsets = UIEdgeInsetsMake(25, 0, 109, 0)
        mainTableView.backgroundColor = UIColor(red: 220/255.0, green: 220/255.0, blue: 220/255.0, alpha: 1)
        return mainTableView
    }()
    
    lazy var topView:UIView = {
        let topView = UIView()
        topView.frame = CGRectMake(0, 0, mainW, 25)
        topView.backgroundColor = UIColor(patternImage: UIImage(named: "navBg")!)
        
        let leftLabel = UILabel()
        leftLabel.frame = CGRectMake(15, 0, mainW/2 - 15, topView.frame.size.height)
        leftLabel.text = "江汉大学北区提货点"
        leftLabel.font = UIFont.systemFontOfSize(14)
        leftLabel.textColor = UIColor.whiteColor()
        topView.addSubview(leftLabel)
        
        let rightLabel = UILabel()
        rightLabel.frame = CGRectMake(CGRectGetMaxX(leftLabel.frame), 0, mainW/2 - 5, 25)
        rightLabel.text = "跟换配送方式>"
        rightLabel.textAlignment = NSTextAlignment.Right
        rightLabel.font = UIFont.systemFontOfSize(14)
        rightLabel.textColor = UIColor.whiteColor()
        topView.addSubview(rightLabel)
        return topView
    }()
    
    lazy var noGoodsView:NoGoodsView = {
        let noGoodsView = NoGoodsView.noGoodsView()
        noGoodsView.frame = UIScreen.mainScreen().bounds
        return noGoodsView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(true)
        setupUI()
       
        mainTableView.reloadData()
    }
    
    private func setupUI(){
        title = "购物车"
        let data = ShoppingGoods.shareShopping().goodsArray
        if data.count == 0 {
            view.addSubview(noGoodsView)
        }else{
            view.addSubview(mainTableView)
             setupBottom()
        }
        
        view.addSubview(topView)
    }
    private func setupBottom(){
        let bgView = UIView()
        bgView.frame = CGRectMake(0, CGRectGetMinY((tabBarController?.tabBar.frame)!) - 60 - 49, mainW, 50)
        bgView.backgroundColor = UIColor.whiteColor()
        view.addSubview(bgView)
        
        let totalString = UILabel()
        totalString.frame = CGRectMake(35, CGRectGetMinY((tabBarController?.tabBar.frame)!) - 55 - 49, 50, 40)
        totalString.font = UIFont.systemFontOfSize(14)
        totalString.textAlignment = NSTextAlignment.Right
        totalString.text = "总计："
        view.addSubview(totalString)
        
        let totalLabel = UILabel()
        totalLabel.frame = CGRectMake(CGRectGetMaxX(totalString.frame) + 5, CGRectGetMinY((tabBarController?.tabBar.frame)!) - 55 - 49, 300, 40)
        totalLabel.font = UIFont.systemFontOfSize(16, weight: 0.2)
        totalLabel.textColor = UIColor.orangeColor()
        totalLabel.text = String(format: "￥%.2lf",calculateTotal())
        total = totalLabel
        view.addSubview(totalLabel)
        
        let  accounting = UIButton()
        accounting.frame = CGRectMake(mainW - 140, CGRectGetMinY((tabBarController?.tabBar.frame)!) - 55 - 49, 120, 35)
       
        accounting.setBackgroundImage(UIImage(named: "navBg")!, forState: UIControlState.Normal)
        accounting.setTitle("去结算", forState: UIControlState.Normal)
        accounting.titleLabel?.font = UIFont.systemFontOfSize(15)
        accounting.clipsToBounds = true
        accounting.layer.cornerRadius = 5
       // accounting.addTarget(self, action: "", forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(accounting)
    }

    private func calculateTotal() ->Double{
        var total:Double = 0
        let data = ShoppingGoods.shareShopping().goodsArray
        let number = ShoppingGoods.shareShopping().numArray
        for i in 0..<data.count{
           let goods = (data[i] as! GoodsModel).laouser
            let price = (goods! as NSString).substringFromIndex(1)
            let realNuber = (number[i] as NSString).substringFromIndex(1)
            total = total + Double(price)! * Double(realNuber)!
        }
        return total
    }
    
}




extension ShoppingViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let data = ShoppingGoods.shareShopping().goodsArray
        return (data.count)
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! ShoppingTableViewCell
        let data = ShoppingGoods.shareShopping().goodsArray
        let goodsMode = data[indexPath.row] as! GoodsModel
        cell.goodsMode = goodsMode
        cell.numberString = ShoppingGoods.shareShopping().numArray[indexPath.row]
        cell.backgroundColor = UIColor.clearColor()
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true )
    }
    
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == UITableViewCellEditingStyle.Delete {
            ShoppingGoods.shareShopping().goodsArray.removeAtIndex(indexPath.row)
            ShoppingGoods.shareShopping().numArray.removeAtIndex(indexPath.row)
            var dict = Array<NSIndexPath>()
            dict.append(indexPath)
            tableView.deleteRowsAtIndexPaths(dict, withRowAnimation: UITableViewRowAnimation.Fade)
            total!.text = String(format: "￥%.2lf",calculateTotal())
            if ShoppingGoods.shareShopping().goodsArray.count == 0{
                setupUI()
            }
        }
    }
}